/*******************************************************************************
*  S&M - MIDI Bus Router & Filter v2.0
*  Copyright 2012, Jeffos                                                      *
*  This program is free software: you can redistribute it and/or modify        *
*  it under the terms of the GNU General Public License as published by        *
*  the Free Software Foundation, either version 3 of the License, or           *
*  (at your option) any later version.                                         *
*                                                                              *
*  This program is distributed in the hope that it will be useful,             *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of              *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                        *
*******************************************************************************/

desc: MIDI Bus Router & Filter

slider1:0<0,16,1{All,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}>Input Bus
slider2:0<0,16,1{All,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}>Input Channel
slider3:0<0,16,1{Source,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}>Output Bus
slider4:0<0,16,1{Source,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}>Output Channel
slider5:1<0,1,1{Filter,Pass-through}>Source events

@init
ext_midi_bus = 1;

@slider
inBus = slider1;
inCh = slider2;
outBus = slider3;
outCh = slider4;
thru = slider5;

remap = (outBus && (!inBus || (inBus && outBus!=inBus)));
remap |= (outCh && (!inCh || (inCh && outCh!=inCh)));

@block
while (
  midirecv(offset, msg1, msg23) ? (
    status = msg1 & $xF0;
    channel = msg1 & $x0F;
    match = (!inBus || midi_bus == (inBus-1));
    match &= (!inCh || channel == (inCh-1));
    (match && remap) ? (
      old_bus = midi_bus;
      midi_bus = (outBus ? outBus-1 : midi_bus);
      midisend(offset, status + (outCh ? outCh-1 : channel), msg23);
      midi_bus = old_bus;          
    );
    (thru || !match) ? midisend(offset, msg1, msg23);
    1;
  );
);

